package com.neu.cloudfactory.controler;

import com.neu.cloudfactory.bean.Equipement.Equipment;
import com.neu.cloudfactory.bean.Loan.Loan;
import com.neu.cloudfactory.repository.EquipmentRepository;
import com.neu.cloudfactory.repository.LoanRepository;
import com.neu.cloudfactory.util.DateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoanControler {
    @Autowired
    LoanRepository loanRepository;
    @Autowired
    EquipmentRepository equipmentRepository;

    @RequestMapping("/loan/add")
    public String add(@RequestBody Loan loan){
        boolean complete = false;
        Equipment equipment;
        try{
            equipment = equipmentRepository.getById(loan.getEquipmentid());
            equipment.setFactoryid(loan.getBorrowerid());
            equipment = equipmentRepository.save(equipment);

            loan.setBorrowdate(DateFormat.parseUTC(loan.getBorrowdate()));
            loan.setReturntime(DateFormat.parseUTC(loan.getReturntime()));

            loan=loanRepository.save(loan);
            complete = loan.getId()!=0 && equipment.getFactoryid()!=0;
        }catch (Exception e){
        }
        return complete?"success":"failed";
    }

    @RequestMapping("/loan/findAll/{page}/{size}")
    public Page<Equipment> loanFindAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        Pageable pageable = PageRequest.of(page-1,size);

        return equipmentRepository.findAllByFactoryidAndBorrowable(0,true,pageable);
    }
}
